package com.njworkorder.HTSingleLogin;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * cas认证成功
 *
 * @author ht_lzc
 * @date 2024/8/2 9:33
 */
@Service
public class CasAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    private static final Logger log = LoggerFactory.getLogger(CasAuthenticationSuccessHandler.class);
    private static final RequestCache requestCache = new HttpSessionRequestCache();

    //private final RedisCache redisCache;


    @Value("${cas.server-url-prefix}")
    private String serverUrlPrefix;
    @Value("${cas.server-login-url}")
    private String serverLoginUrl;
    @Value("${cas.client-host-url}")
    private String serviceHostUrl;
    @Value("${cas.ignore-host-url}")
    private String ignoreHostUrl;
    @Value("${cas.client-redirect-url}")
    private String redirectUrl;
    @Value("${cas.enable}")
    private Boolean casEnable;
    // 令牌有效期（默认30分钟）
    @Value("${token.expireTime}")
    private int expireTime;

    private final TokenService tokenService;
    public CasAuthenticationSuccessHandler(TokenService tokenService) {
        this.tokenService = tokenService;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
        String targetUrlParameter = getTargetUrlParameter();
        if (isAlwaysUseDefaultTargetUrl() || (targetUrlParameter != null && StringUtils.hasText(request.getParameter(targetUrlParameter)))) {
            requestCache.removeRequest(request, response);
            super.onAuthenticationSuccess(request, response, authentication);
            return;
        }
        clearAuthenticationAttributes(request);
        LoginUser userDetails = (LoginUser) authentication.getPrincipal();

        String token = tokenService.createToken(userDetails, true);
        // 打印日志
        log.info("CAS认证中心的ticket:{}", authentication.getCredentials().toString());
        // 往Redis中设置token
        //redisCache.setCacheObject(CacheConstants.LOGIN_TICKET_KEY+authentication.getCredentials().toString(), token, expireTime, TimeUnit.MINUTES);
        // 往Cookie中设置token
        Cookie casCookie = new Cookie(Constants.WEB_TOKEN_KEY, token);
        //casCookie.setMaxAge(expireTime * 60);
        // TODO: 设置 cookie path 为 根目录(解决前端 cookie 丢失问题), 不确定 是否合理
        casCookie.setPath("/");
        response.addCookie(casCookie);
        // 设置后端认证成功标识
        //HttpSession httpSession = request.getSession();
        //httpSession.setAttribute(Constants.CAS_TOKEN, token);
        //httpSession.setMaxInactiveInterval(expireTime * 60);
        // 登录成功后跳转到前端登录页面
        getRedirectStrategy().sendRedirect(request, response, redirectUrl);
    }


}
